﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Abp.Web.Models;
using Batman.Jianbei.Forum.Controllers.Dicts.PartitionInputs;
using Batman.Jianbei.Forum.Core.Domains.Dicts;
using Microsoft.EntityFrameworkCore;
using Omu.ValueInjecter;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Jianbei.Forum.Services.Dicts
{
    public class PartitioManager : ApplicationService
    {
        public IRepository<Partition, string> Repository { get; set; }

        /// <summary>
        /// 创建分区
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<AjaxResponse> CreateAsync(PartitionCreateInput model)
        {
            var isExists = Repository.GetAll().AsNoTracking().Where(t => t.NormalizedName == model.NormalizedName).Any();

            if (isExists)
            {
                return new AjaxResponse { Success = false, Error = new ErrorInfo($"分区已存在:{model.NormalizedName}") };
            }

            model.Name = model.Name ?? model.NormalizedName;

            var entity = ObjectMapper.Map<Partition>(model);
            entity.CreateAt = DateTime.Now;
            var result = await Repository.InsertAsync(entity);

            return new AjaxResponse { Success = true, Result = result };
        }

        /// <summary>
        /// 更新分区
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<AjaxResponse> UpdateAsync(PartitionUpdateInput model)
        {
            var isExists = Repository.GetAll().AsNoTracking().Where(t => t.NormalizedName == model.NormalizedName && t.Id != model.Id).Any();

            if (isExists)
                return new AjaxResponse { Success = false, Error = new ErrorInfo($"分区已存在:{model.NormalizedName}") };

            var old = await Repository.GetAll().AsNoTracking().FirstOrDefaultAsync(t => t.Id == model.Id);

            if (old == null)
                return new AjaxResponse { Success = false, Error = new ErrorInfo($"分区不存在:{model.NormalizedName}") };

           old.InjectFrom(model);

            //old.InjectFrom<Partition>(model);
            var result = await Repository.UpdateAsync(old);

            return new AjaxResponse { Success = true, Result = result };
        }

        /// <summary>
        /// 删除分区
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<AjaxResponse> DeleteAsync(string id)
        {
            await Repository.DeleteAsync(t => t.Id == id);

            return new AjaxResponse { Success = true };
        }
    }
}
